//
//  TaoLunVC.m
//  ZhiBoYuan
//
//  Created by apple on 2018/5/9.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "TaoLunVC.h"
#import "TaoLunCell.h"

#import "TaoLun.h"

static NSString *ident = @"TaoLunCell";

@interface TaoLunVC ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property (nonatomic, strong) NSMutableArray *dataArray;
//@property (nonatomic, strong) UITableView *tableView;

@property(nonatomic,strong)AxcEmptyDataTableView *tableView;

@property (nonatomic, assign) int pageIndex;

@property(nonatomic,assign)NSInteger visibleRow;


@property(nonatomic, strong)UIButton *topButton;

//@property(nonatomic,strong)TaoLun *taoLunView;


@end

@implementation TaoLunVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"发表";
    
    _pageIndex = 1;
    
    [self loadData];
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.topButton];

}

-(void)setTask:(Task *)task{
    _task = task;
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    if (self.fresh) {
        
        _task.pineLuncount = [NSString stringWithFormat:@"%zd",_dataArray.count];
        
        self.fresh(_task);
    }
}

-(void)loadData{
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       @"task_id":_course_id,
                       @"page":[NSString stringWithFormat:@"%d",_pageIndex],
                       @"page_count":@"10"
                       };
    
    NSString *lastUrl  = @"g=Client&m=Comment&a=taskCommentList";
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        if (_pageIndex == 1) {
            [self.dataArray removeAllObjects];
        }
        if ([responseObject[@"status"] intValue] == 200) {
            for (NSDictionary *dicc in responseObject[@"data"][@"comment_list"]) {
                [self.dataArray addObject:dicc];
            }
            
            if (self.dataArray.count <4) {
                self.tableView.mj_footer.hidden = YES;
            }else{
                
                self.tableView.mj_footer.hidden = NO;
            }
            
            [self.tableView reloadData];
        }else{
            [MBProgressHUD showTextOnly:self.view message:responseObject[@"msg"] delay:2.0];
            
        }
        
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}

#pragma mark -----------------------  讨论  ------------------------
- (void)taoLunSender:(UIButton *)sender
{
    AppDelegate *app =(AppDelegate *) [UIApplication sharedApplication].delegate;
    
    TaoLun *tl = [[TaoLun alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    tl.course_id = self.course_id;
    
    tl.block = ^{
        [self loadData];
    };
    
    [app.window addSubview:tl];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TaoLunCell *cell = [tableView dequeueReusableCellWithIdentifier:ident forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    
    [cell.imageHead sd_setImageWithURL:[NSURL URLWithString:[_dataArray[indexPath.row][@"user_info"] valueForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"0009"]];
    cell.imageHead.layer.masksToBounds = YES;
    cell.imageHead.layer.cornerRadius = cell.imageHead.frame.size.width/2;
    
    cell.nameLable.text = [_dataArray[indexPath.row][@"user_info"] valueForKey:@"name"];
    cell.detialLabel.text = [_dataArray[indexPath.row] valueForKey:@"content"];
    cell.timeLabel.text = [NSString stringWithFormat:@"%@",[self.dataArray[indexPath.row] valueForKey:@"create_time"]];

    return cell;
}

- (UITableView *)tableView {
    if (!_tableView) {
        AxcEmptyDataTableView *  tableView = [[AxcEmptyDataTableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT -HOME_INDICATOR_HEIGHT) style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.delegate        = self;
        tableView.dataSource      = self;
        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
        
        tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
        
        
        
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        //        self.extendedLayoutIncludesOpaqueBars = YES;
        
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        //        if (iPhoneX) {
        //            tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        //            tableView.scrollIndicatorInsets = _tableView.contentInset;
        //        }
        
        
        
        [tableView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellReuseIdentifier:ident];
        
        [tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        __weak __typeof(&*self)weakSelf = self;
        
        // 下拉刷新
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            weakSelf.pageIndex = 1;
            
                        [weakSelf loadData];
            
            
        }];
        
        
        //         上拉加载
        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            if ( weakSelf.pageIndex < -1 )
            {
                weakSelf.pageIndex = 1;
            }
            weakSelf.pageIndex++;
                        [weakSelf loadData];
            
        }];
        
        
        
        self.placeholderView.frame = tableView.bounds;
        
        // 设置空集时候展示的View
        tableView.axcUI_placeHolderView = self.placeholderView;
        
        //  默认YES 自带渐入渐出动画效果，下边这个参数可以关闭
        tableView.axcUI_placeHolderViewAnimations = NO;
        
        // 占位View的“重新加载”按钮的Block回调:
        __weak typeof(self) WeakSelf = self;
        
        self.placeholderView.clickLoadBtnBlock = ^(id type) {
            //        WeakSelf.dataArray = nil;
            
            [self loadData];
            
        };
        
        _tableView = tableView;
        
    }
    return _tableView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        
        _dataArray= [NSMutableArray array];
    }
    return _dataArray;
}

-(UIButton *)topButton
{
    if (!_topButton)
    {
        _topButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _topButton.frame = CGRectMake(SCREEN_WIDTH-70, SCREEN_HEIGHT-90-HOME_INDICATOR_HEIGHT, 50, 50);
        [_topButton setBackgroundImage:[UIImage imageNamed:@"发表"] forState:(UIControlStateNormal)];
        
        _topButton.layer.masksToBounds = YES;
        
        _topButton.layer.cornerRadius = _topButton.frame.size.width/2 ;
        
        [_topButton setBackgroundColor:[UIColor whiteColor]];
        
        [_topButton addTarget:self action:@selector(taoLunSender:) forControlEvents:(UIControlEventTouchUpInside)];
        
        
//        _topButton.layer.borderWidth = 1;
        
//        _topButton.layer.borderColor = hui3Color.CGColor;
        
        
    }
    return _topButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
